<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Option;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Layout\Content;

class WithdrawConfigController extends Controller
{
    use HasResourceActions;
    private $name = '提现设置';

    public function get(Content $content)
    {
        //获取信息
        $info = Option::where('key', config('set.withdraw'))->first();
        if ($info) {
            return $content
                ->header($this->name)
                ->description(trans('admin.edit'))
                ->body($this->form()->edit($info->id));

        } else {
            return $content
                ->header($this->name)
                ->description(trans('admin.create'))
                ->body($this->form());
        }
    }

    public function save(Content $content)
    {
        //获取信息
        $info = Option::where('key', config('set.withdraw'))->first();
        if ($info) {
            return $this->form()->update($info->id);
        } else {
            return $this->form()->store();
        }
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Option);

        $form->hidden('key')->default(config('set.withdraw'));
        $form->hidden('value');

        $array = get_withdraw_option();

        $form->text('min', '最低提现金额(分)')->rules('required|regex:/^\d+$/', ['regex' => '请输入非负整数'])
            ->default(function () use ($array) {
                return $array['min'];
            });
        $form->text('withdraw_time', '提现n次后需要关注公众号')->rules('required|regex:/^\d+$/', ['regex' => '请输入非负整数'])
            ->default(function () use ($array) {
                return $array['withdraw_time'];
            });

        $form->ignore(['min', 'withdraw_time']);

        $form->tools(function (Form\Tools $tools) {
            // 去掉`列表`按钮
            $tools->disableList();
            // 去掉`删除`按钮
            $tools->disableDelete();
            // 去掉`查看`按钮
            $tools->disableView();
        });
        $form->footer(function ($footer) {
            // 去掉`查看`checkbox
            $footer->disableViewCheck();
            // 去掉`继续编辑`checkbox
            $footer->disableEditingCheck();
            // 去掉`继续创建`checkbox
            $footer->disableCreatingCheck();
        });

        $form->saving(function (Form $form) {
            $min = request()->input('min');
            $withdrawTime = request()->input('withdraw_time');
            $form->value = json_encode(['min' => $min, 'withdraw_time' => $withdrawTime]);
        });

        $form->setAction(admin_base_path('withdrawconfig/save'));
        $form->saved(function () {
            set_option_cache(config('set.withdraw'));
            admin_toastr(trans('admin.update_succeeded'));
            return redirect(admin_base_path('withdrawconfig/get'));
        });

        return $form;
    }
}
